import {Store} from 'iflux2';
import WebApi from './webApi';
import {fromJS} from 'immutable';

import {message} from 'antd';

import TradeActor from './actor/trade-actor';
import GoodsActor from './actor/goods-actor';
import {OrderType, GoodsType} from './constant/action-type';

import calculator from 'util/calculator';


export default class AppStore extends Store {

    bindActor() {
        return [
            new TradeActor,
            new GoodsActor
        ]
    }

    constructor(props) {
        super(props);

        window._store = this
    }


    /**
     * 查询订单详情
     * @param tid
     * @returns {Promise.<void>}
     */
    queryOrder = async (tid)=>{
        try {
            const {tradeOrder:{itemOrders, ...rest}, taxRate, userLogo} = await WebApi.queryOrderDetail(tid);
            this.dispatch(OrderType.SET_DETAIL, fromJS(rest));
            //过滤赠品，设置改价类型
            this.dispatch(GoodsType.SET_ITEM_ORDER, fromJS(itemOrders).filter(item=>item.get('isGift') == 0).map(item=>item.set('type', 0)));
            this.dispatch(OrderType.SET_TAX_RAT, taxRate);
            this.dispatch(OrderType.SET_USER_LOGO, userLogo);
        } catch(err) {
            message.error(err.message);
            return Promise.reject(err);
        }
    }


    changeNum = (num, index)=>{
        this.dispatch(GoodsType.SET_NUM, {num, index});
    }


    changePrice = (price, type, index)=>{
        this.dispatch(GoodsType.SET_PRICE, {price, type, index});
    }


    changeOrderField = (value, field)=>{
        this.dispatch(OrderType.SET_FIELD_VALUE, {value, field});
    }


    save = async ()=>{
        const allState = this.state();

        let order = allState.get('order');
        let itemOrders = allState.get('itemOrders');

        let params = {
            tid: order.get('tid'),
            logisticsFee: order.get('logisticsFee'),
            invoiceFee: this.calculateInvoiceFee(),
            itemRequestList: itemOrders.map(item=>{
                return {
                    oid: item.get('oid'),
                    itemNumber: item.get('itemNumber'),
                    levelPrice: item.get('pervalue')
                }
            }).toArray()
        };

        try {
            await WebApi.changePrice(params);
            message.success('修改成功');
        } catch(err) {
            message.error(err.message.split(':')[0]);
            return Promise.reject(err);
        }
    }


    calculateInvoiceFee = ()=>{
        const allState = this.state();

        let itemTotal = allState.get('itemOrders').reduce((total, item)=>{
            return calculator.floatAdd(total, calculator.floatMul(item.get('pervalue'), item.get('itemNumber')))
        }, 0);

        return Math.floor(
            calculator.floatMul(calculator.floatSub(itemTotal, allState.getIn(['order', 'offsetMoney']))
                , allState.get('taxRate'))
        ) / 100;


    }
}